<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Good;
use App\Goodsimg;
use Storage;
class ImgController extends Controller{
    public function upload(){
        //取出商品货号与商品名称展示到模板
        $goods = Good::get();
        return view('admin/uploadimg',['goods'=>$goods]);
    }
    //上传图片
    public function uploadpost(Request $req){
        $goods = Good::find($req->gid);
        $path = $this->datepath();
        $name = $this->name().".jpg";
        $rs = $req->file('pic')->move($path,$name);
        if($rs){
            $patt = "/(?=uploads).+$/";
            preg_match_all($patt,$path,$res);
            $path = '/'.$res[0][0];
            //存入数据库
            $goodsimg = new Goodsimg();
            $goodsimg->goods_name = $goods->goods_name;
            $goodsimg->goods_sn = $goods->goods_sn;
            $goodsimg->gid = $req->gid;
            $goodsimg->url = $path.$name;
            $goodsimg->pubtime = time();
            $goodsimg->save();
            echo "1";
        }else{
            echo "0";
        }
    }

    //图片空间
    public function imglist($sn = 0,$gid = 0){
        $goodimg = Goodsimg::get();
        return view('admin/goodsimg',['goods'=>$goodimg]);
    }

    //删除图片
    public function imgdel($img_id){
        $img = Goodsimg::find($img_id);
        $rs = $img->delete();
        if($rs){
            unlink(base_path().'/public'.$img->url);
            return redirect('img/list');
        }
    }

    //ajax修改图片
    public function imgupdate(Request $req){
        $id = $req->img_id;
        $goodsimg = Goodsimg::find($id);
        //$goodsimg->url = $req->url;
        //执行上传图片
        $path = $this->datepath();
        $name = $this->name().".jpg";
        $rs = $req->file('pic')->move($path,$name);
        if($rs) {
            //删除原图
            //dd(base_path().'/public'.$req->url);
            unlink(base_path().'/public'.$req->url);
            $path = $path.$name;
            $patt = "/(?=uploads).+$/";
            preg_match_all($patt, $path, $res);
            $path = '/' . $res[0][0];
            //在数据库中修改url
            $goodsimg->url = $path;
            $goodsimg->pubtime = time();
            $goodsimg->save();
            return $path;
        }
        return 0;
    }
    //按日期生成目录
    public function datepath(){
        $datepath = date('Ymd');
        $gpath = base_path();
        $path = $gpath.'/public/uploads/'.$datepath.'/';
        //echo $path;
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        return $path;
    }
    //生成随机文件名
    public function name(){
        $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = substr(str_shuffle($str),0,5);
        return $str;
    }
}
